#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-12-15 15:40:03
# @Author  : KlausQiu
# @QQ      : 375235513
# @github  : https://github.com/KlausQIU

# from HuobiUtil import *
from exchangeConnection.houbipro.HuobiProUtil import *
'''
Market data API
'''

# 获取KLine
def get_kline(symbol, period,size, long_polling=None):
    """
    :param symbol: 可选值：{ ethcny }
    :param period: 可选值：{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
    :param long_polling: 可选值： { true, false }
    :return:
    """
    params = {'symbol': symbol,
              'period': period,
              'size':size}

    if long_polling:
        params['long-polling'] = long_polling
    url = MARKET_URL + '/market/history/kline'
    return http_get_request(url, params)


# 获取marketdepth
def get_depth(symbol, type, long_polling=None):
    """
    :param symbol: 可选值：{ ethcny }
    :param type: 可选值：{ percent10, step0, step1, step2, step3, step4, step5 }
    :param long_polling: 可选值： { true, false }
    :return:
    """
    params = {'symbol': symbol,
              'type': type}

    if long_polling:
        params['long-polling'] = long_polling
    url = MARKET_URL + '/market/depth'
    return http_get_request(url, params)


# 获取tradedetail
def get_trade(symbol, long_polling=None):
    """
    :param symbol: 可选值：{ ethcny }
    :param long_polling: 可选值： { true, false }
    :return:
    """
    params = {'symbol': symbol}
    if long_polling:
        params['long-polling'] = long_polling
    url = MARKET_URL + '/market/trade'
    return http_get_request(url, params)


# 获取 Market Detail 24小时成交量数据
def get_detail(symbol, long_polling=None):
    """
    :param symbol: 可选值：{ ethcny }
    :param long_polling: 可选值： { true, false }
    :return:
    """
    params = {'symbol': symbol}
    if long_polling:
        params['long-polling'] = long_polling
    url = MARKET_URL + '/market/detail'
    return http_get_request(url, params)

# 查询系统支持的所有交易对
def get_symbols():
    """
    :return:
    """
    url = MARKET_URL + '/v1/common/symbols'
    params = {}
    return http_get_request(url,params)

'''
Trade/Account API   交易API  ----------------------------------------------------------------------------
'''
def get_accounts():
    """
    :return: 
    """
    path = "/v1/account/accounts"
    params = {}
    return api_key_get(params, path)


# 获取当前账户资产
def get_balance(acct_id=None):
    """
    :param acct_id
    :return:
    """

    if not acct_id:
        try:
            accounts = get_accounts()
            acct_id = ACCOUNT_ID = accounts['data'][0]['id']
        except BaseException as e:
            #print ('get acct_id error.%s'% eacct_id = ACCOUNT_ID)
            print('错误')

    url = "/v1/account/accounts/{0}/balance".format(acct_id)
    params = {"account-id": acct_id}
    return api_key_get(params, url)


# 下单
def orders(amount, source, symbol, _type, price=0):
    """
    
    :param amount:   限价单表示下单数量，市价买单时表示买多少钱，市价卖单的时候表示卖多少币
    :param source:   订单来源  api，如果使用借贷资产交易，请填写'margin-api'
    :param symbol: 
    :param _type: 可选值 {buy-market：市价买, sell-market：市价卖, buy-limit：限价买, sell-limit：限价卖}
    :param price:  下单价格，市价单不传改参数
    :return: 
    """
    try:
        accounts = get_accounts()
        acct_id = accounts['data'][0]['id']
    except BaseException as e:
        print ('get acct_id error.%s'%e)
        acct_id = ACCOUNT_ID

    params = {"account-id": acct_id,
              "amount": amount,
              "symbol": symbol,
              "type": _type,
              "source": source}
    if price:
        params["price"] = price

    url = "/v1/order/orders"
    return api_key_post(params, url)


# 执行订单
def place_order(order_id):
    """
    
    :param order_id: 
    :return: 
    """
    params = {}
    url = "/v1/order/orders/{0}/place".format(order_id)
    return api_key_post(params, url)

#创建并执行订单
def send_order(amount, source, symbol, _type, price=0):
    """
    :param amount:   限价单表示下单数量，市价买单时表示买多少钱，市价卖单时表示卖多少币
    :param source:   订单来源 api，如果使用借贷资产交易，请填写‘margin-api’
    :param symbol:   交易对
    :param _type:   可选值 {buy-market：市价买, sell-market：市价卖, buy-limit：限价买, sell-limit：限价卖}
    :param price:  下单价格，市价单不传该参数
    :return: {
                  "status": "ok",
                  "data": "59378"
                }
    """
    try:
        accounts = get_accounts()
        acct_id = accounts['data'][0]['id']
    except BaseException as e:
        print ('get acct_id error.%s'%e)
        acct_id = ACCOUNT_ID

    params = {"account-id": acct_id,
              "amount": amount,
              "symbol": symbol,
              "type": _type,
              "source": source}
    if price:
        params["price"] = price

    url = '/v1/order/orders/place'
    return api_key_post(params, url)


# 撤销订单
def cancel_order(order_id):
    """
    
    :param order_id: 
    :return: 
    """
    params = {}
    url = "/v1/order/orders/{0}/submitcancel".format(order_id)
    return api_key_post(params, url)


# 查询某个订单
def order_info(order_id):
    """
    
    :param order_id: 
    :return: 
    """
    params = {}
    url = "/v1/order/orders/{0}".format(order_id)
    return api_key_get(params, url)


# 查询某个订单的成交明细
def order_matchresults(order_id):
    """
    
    :param order_id: 
    :return: 
    """
    params = {}
    url = "/v1/order/orders/{0}/matchresults".format(order_id)
    return api_key_get(params, url)


# 查询当前委托、历史委托
def orders_list(symbol, states, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
    """
    :param symbol: 
    :param states: 可选值 {pre-submitted 准备提交, submitted 已提交, partial-filled 部分成交, partial-canceled 部分成交撤销, filled 完全成交, canceled 已撤销}
    :param types: 可选值 {buy-market：市价买, sell-market：市价卖, buy-limit：限价买, sell-limit：限价卖}
    :param start_date: 
    :param end_date: 
    :param _from: 
    :param direct: 可选值{prev 向前，next 向后}
    :param size: 
    :return: 
    """
    params = {'symbol': symbol,
              'states': states}

    if types:
        params[types] = types
    if start_date:
        params['start-date'] = start_date
    if end_date:
        params['end-date'] = end_date
    if _from:
        params['from'] = _from
    if direct:
        params['direct'] = direct
    if size:
        params['size'] = size
    url = '/v1/order/orders'
    return api_key_get(params, url)


# 查询当前成交、历史成交
def orders_matchresults(symbol, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
    """
    :param symbol: 
    :param types: 可选值 {buy-market：市价买, sell-market：市价卖, buy-limit：限价买, sell-limit：限价卖}
    :param start_date: 
    :param end_date: 
    :param _from: 
    :param direct: 可选值{prev 向前，next 向后}
    :param size: 
    :return: 
    """
    params = {'symbol': symbol}

    if types:
        params[types] = types
    if start_date:
        params['start-date'] = start_date
    if end_date:
        params['end-date'] = end_date
    if _from:
        params['from'] = _from
    if direct:
        params['direct'] = direct
    if size:
        params['size'] = size
    url = '/v1/order/matchresults'
    return api_key_get(params, url)


# 申请提现虚拟币
def withdraw(address_id, amount,currency,fee=0,addrtag=''):
    """
    :param address_id:
    :param amount:
    :param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种)
    :param fee:
    :param addr-tag:
    :return: {
              "status": "ok",
              "data": 700
            }
    """
    params = {'address-id': address_id,
              'amount': amount,
              "currency":currency,
              "fee":fee,
              "addr-tag":addrtag}
    url = '/v1/dw/withdraw/api/create'
    return api_key_post(params, url)

# 申请取消提现虚拟币
def cancel_withdraw(address_id):
    """
    
    :param address_id: 
    :return: {
              "status": "ok",
              "data": 700
            }
    """
    params = {}
    url = '/v1/dw/withdraw-virtual/{0}/cancel'.format(address_id)
    return api_key_post(params, url)



#---------------------------------------------------------------------------------------------------------------------扩展
from decimal import *
def getMinimumOrderQty(symbo):
    """
    得到货币对最小交易单位
    :param symbo:{"base-currency": 'btc',"quote-currency": 'usdt'}
    :return: {
            'price-precision':,0.01                  #交易价格最小单位
            'amount-precision':0.0001                #交易数量最小单位
            len('amount-precision')                  #最小交易数据位数
    }
    """
    listtem=get_symbols() #得到所有交易对
    minimum=10
    weishu=0
    for v in listtem['data']:    #从所有交易对中找到当前的交易对  并使用todecimal函数返回最小交易单位
        if v['base-currency']==symbo['base-currency'] and v['quote-currency'] == symbo['quote-currency']:
            #return {'price-precision': todecimal(v['price-precision']),'amount-precision': todecimal(v['amount-precision'])}
            return todecimal(v['price-precision']),todecimal(v['amount-precision']),v['amount-precision']


#得到特定交易对的结余
def get_symbol_balance(base_symbol,quote_symbol):
    """

    :param base_symbol:   基础  btc
    :param quote_symbol:  引用  usdt
    :return:  {'btc': {'trade': '0.000000000000000000', 'frozen': '0.000000000000000000'}, 'usdt': {'trade': '0.001593200000000000', 'frozen': '0.000000000000000000'}}
    """
    balance=get_balance()
    balancedict={base_symbol:{},quote_symbol:{}}
    if balance.get('status')=='ok':
        for i in balance['data']['list']:
            if i['currency']==base_symbol and i['type']=='trade':
                balancedict[base_symbol]['trade'] = float(i['balance'])
            if i['currency']==base_symbol and i['type']=='frozen':
                balancedict[base_symbol]['frozen']=float(i['balance'])

            if i['currency']==quote_symbol and i['type']=='trade':
                balancedict[quote_symbol]['trade']=float(i['balance'])
            if i['currency']==quote_symbol and i['type']=='frozen':
                balancedict[quote_symbol]['frozen']=float(i['balance'])
        return balancedict





#---------------------------------------------------------------------------------------------------------------------------------工具

#根据出入的小数位数生成标注小数
def todecimal(weishu):
    """
    :param weishu:  需要生成的小数位数
    :return:    0.0X1   返回
    """
    decimal=10
    for i in range(weishu-1):
        decimal=decimal*10
    return round(Decimal(1 / decimal), weishu)


if __name__ == '__main__':
    #print(get_symbols())    #得到所有交易货币对
    #print(get_kline("btcusdt","1day",150,False))                           #得到模拟k线
    #print(get_depth('btcusdt','step0'))                                    #得到行情深度
    #print(get_accounts())
    #print(get_balance('152288'))
    #print(send_order(amount='0.01',price='200',source='api',symbol='ethusdt',_type='buy-limit'))  #下单
    #print(getMinimumOrderQty({'base-currency': 'btc','quote-currency': 'usdt'}))  #得到最小交易单位
    #print(get_balance())                 #得到账户所有币种结余
    #print(get_symbol_balance('btc','usdt'))           #得到特定币种结余

    # huobiDepth=get_depth('btcusdt', 'step1')
    # print(huobiDepth)
    # huobi_sell_1_price = huobiDepth["tick"]["asks"][0][0]
    # huobi_sell_1_qty = huobiDepth["tick"]["asks"][0][1]
    # huobi_buy_1_price = huobiDepth["tick"]["bids"][0][0]
    # huobi_buy_1_qty = huobiDepth["tick"]["bids"][0][1]

    # okcoin_sell_1_price = okcoinDepth["asks"][0][0]
    # okcoin_sell_1_qty = okcoinDepth["asks"][0][1]
    # okcoin_buy_1_price = okcoinDepth["bids"][0][0]
    # okcoin_buy_1_qty = okcoinDepth["bids"][0][1]


    a=order_info('640853322')
    print(a)
    print(a['data']["state"]=='filled')